/*
 * Copyright 2002-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.org.jglab.framework;

import cn.org.jglab.framework.git.GitHookExtension;
import org.gradle.api.Plugin;
import org.gradle.api.Project;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;


/**
 * 插件实现
 */
public class GitHookPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        // 创建扩展
        GitHookExtension extension = project.getExtensions().create("gitHook", GitHookExtension.class);

        // 安装 hook
        project.getTasks().register("installGitHook", task -> task.doLast(t -> {
            File hooksDir = new File(project.getRootDir(), ".git/hooks");
            if (!hooksDir.exists()) {
                hooksDir.mkdirs();
            }
            File preCommitSource = new File(project.getRootDir(), "buildSrc/git-hooks/pre-commit");
            File preCommitTarget = new File(hooksDir, "pre-commit");

            String config = "# Auto-generated by cn.org.jglab.framework.GitHookPlugin\n" +
                    "PREFER_GLOBAL_GRADLE=" + extension.isPreferGlobalGradle() + "\n" +
                    "SKIP_HOOK_ENV_VAR=" + extension.getSkipHookEnvVar() + "\n";

            try {
                String content = config + new String(Files.readAllBytes(preCommitSource.toPath()));
                Files.write(preCommitTarget.toPath(), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                preCommitTarget.setExecutable(true);

                System.out.println("Git pre-commit hook installed with configuration:");
                System.out.println("  PREFER_GLOBAL_GRADLE=" + extension.isPreferGlobalGradle());
                System.out.println("  SKIP_HOOK_ENV_VAR=" + extension.getSkipHookEnvVar());
            } catch (IOException e) {
                throw new RuntimeException("Failed to install git hook", e);
            }
        }));

        // 删除 hook
        project.getTasks().register("removeGitHook", task -> task.doLast(t -> {
            File preCommitTarget = new File(project.getRootDir(), ".git/hooks/pre-commit");
            if (preCommitTarget.exists() && preCommitTarget.delete()) {
                System.out.println("Git pre-commit hook removed successfully.");
            } else {
                System.out.println("No pre-commit hook to remove.");
            }
        }));

        System.out.println("cn.org.jglab.framework.GitHookPlugin applied. Use 'installGitHook' and 'removeGitHook' tasks.");
    }
}
